<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        canvas {
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="490" height="220"></canvas>
    <br>
    <button id="btn">clear</button>
    <script type="text/javascript" src="./jq1.9.js"></script>
    <script>
        var c = document.getElementById('canvas');
        var context = document.getElementById('canvas').getContext("2d");
        var clickX = new Array();
        var clickY = new Array();
        var clickDrag = new Array(); //存储路径点
        var paint; //是否绘制，mousedown时置为true
        function addClick(x, y, dragging) {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }
        $("#btn").on("click", function () {
            c.height = c.height;
            clickDrag = []
            clickX = []
            clickY = []
        })

        function RandomNumBoth(Min, Max) {
            var Range = Max - Min; console.log(Range)
            var Rand = Math.random();console.log(Rand)
            var num = Min + Math.round(Rand * Range); //四舍五入
            return num;
        }

        function redraw() {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height); // 清除画布内容

            context.strokeStyle = "#df4b26"; //设置线条颜色
            context.lineJoin = "round"; //当两条线条交汇时，创建圆形边角
            context.lineWidth = 5; //线条粗细

            for (var i = 0; i < clickX.length; i++) {
                context.beginPath(); //开始一条路径，或重置当前的路径
                if (clickDrag[i] && i) {
                    context.moveTo(clickX[i - 1], clickY[i - 1]);
                } else {
                    context.moveTo(clickX[i] - 1, clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke(); //绘制路径
            }
        }
        $('#canvas').mousedown(function (e) {
            var mouseX = e.pageX - this.offsetLeft;
            var mouseY = e.pageY - this.offsetTop;
            paint = true;
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
            redraw();
        });
        $('#canvas').mousemove(function (e) {
            if (paint) {
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                redraw();
            }
        });
        $('#canvas').mouseup(function (e) {
            paint = false;
        });
        $('#canvas').mouseleave(function (e) {
            paint = false;
        });
    </script>
</body>

</html>